package com.xunlai.infra.permission.business.controller;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.xunlai.infra.permission.business.dao.entity.Order;
import com.xunlai.infra.permission.business.service.OrderService;
import com.xunlai.infra.permission.common.vo.BaseResponse;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author liang
 * @date 9/5/23 4:14 PM
 */
@RestController
@RequestMapping("/travel/manage/order")
public class OrderController {

    private final Logger logger = LoggerFactory.getLogger(OrderController.class);

    private Config config;

    private OrderService orderService;

    public BaseResponse<String> createWxNativePayOrder(){

        return BaseResponse.success("");
    }



    @PostMapping("wxpay/notify")
    public ResponseEntity wxNativePayNotify(HttpServletRequest request, @RequestBody String requestBody){
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatpayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(requestBody)
                .build();

// 初始化 NotificationParser
        NotificationParser parser = new NotificationParser((NotificationConfig) config);
        String orderNo;
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            orderNo = transaction.getOutTradeNo();
            String openid = transaction.getPayer().getOpenid();

        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            logger.error("sign verification failed", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        try {
            orderService.paySuccess(orderNo);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

// 如果处理失败，应返回 4xx/5xx 的状态码，例如 500 INTERNAL_SERVER_ERROR

// 处理成功，返回 200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK).build();
    }


    @GetMapping("isPaid/{orderId}")
    public BaseResponse<Boolean> isPaid(@PathVariable Long orderId){
        int orderStatus = orderService.orderStatus(orderId);
        return BaseResponse.success(orderStatus == Order.OrderStatus.PAID.getStatus() || orderStatus == Order.OrderStatus.COMPLETE.getStatus() );
    }

    @Autowired
    public void setConfig(Config config) {
        this.config = config;
    }

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
}
